﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.IO;
using System.Linq;

namespace HRX.PayCenter.Common.WebAppBase
{
    /// <summary>
    /// 添加Swagger帮助类
    /// </summary>
    public static class SwaggerHelper
    {
        private static SwaggerSettings _settings;

        /// <summary>
        /// 注册Swagger
        /// </summary>
        /// <param name="services"></param>
        public static IServiceCollection AddSwaggerConfig(this IServiceCollection services, SwaggerSettings settings)
        {
            _settings = settings;
            if (_settings == null)
            {
                Console.WriteLine("该项目Swagger设置为空，Swagger功能将不可用。");
                return services;
            }
            if (!_settings.IsEnable)
            {
                Console.WriteLine($"Swagger功能不可用 IsEnable=false");
                return services;
            }
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc(_settings.Version, new Info
                {
                    Version = _settings.Version,
                    Title = _settings.Title
                });
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                if (_settings.IncludeXml == null || !_settings.IncludeXml.Any())
                {
                    return;
                }
                foreach (var xmlfile in _settings.IncludeXml)
                {
                    var xmlPath = Path.Combine(basePath, xmlfile);
                    options.IncludeXmlComments(xmlPath);
                }
            });
            return services;
        }

        /// <summary>
        /// 在Startup的Configure调用
        /// </summary>
        /// <param name="app"></param>
        /// <param name="settings"></param>
        public static IApplicationBuilder UseSwagger(this IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            try
            {
                if (!_settings.IsEnable)
                {
                    loggerFactory?.CreateLogger("SwaggerHelper").LogInformation($"Swagger功能已禁用 IsEnable=false");
                    return app;
                }
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint(_settings.Url, _settings.Name);
                });
            }
            catch (Exception ex)
            {
                loggerFactory?.CreateLogger("SwaggerHelper").LogError($"UseSwagger异常，Swagger功能将不可用。Swagger设置为：{_settings.Url}，异常信息：{ex}");
            }
            return app;
        }
    }
}
